<template>
  <div class="batch-upload-container">
    <a-card title="批量上传图片" :bordered="false">
      <!-- 上传配置 -->
      <div class="upload-config">
        <a-form :model="uploadConfig" layout="vertical">
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-item label="命名策略" name="nameStrategy">
                <a-select v-model:value="uploadConfig.nameStrategy" placeholder="选择命名策略">
                  <a-select-option value="auto">自动命名</a-select-option>
                  <a-select-option value="filename">使用文件名</a-select-option>
                  <a-select-option value="custom">自定义命名</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8" v-if="uploadConfig.nameStrategy === 'custom'">
              <a-form-item label="名称前缀" name="namePrefix">
                <a-input v-model:value="uploadConfig.namePrefix" placeholder="请输入名称前缀" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="标签策略" name="tagStrategy">
                <a-select v-model:value="uploadConfig.tagStrategy" placeholder="选择标签策略">
                  <a-select-option value="ai">AI生成</a-select-option>
                  <a-select-option value="custom">自定义标签</a-select-option>
                  <a-select-option value="none">不设置标签</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="24" v-if="uploadConfig.tagStrategy === 'custom'">
            <a-col :span="16">
              <a-form-item label="自定义标签" name="customTags">
                <a-select
                  v-model:value="uploadConfig.customTags"
                  mode="tags"
                  placeholder="输入标签后按回车添加"
                  :max-tag-count="10"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-item label="分类策略" name="categoryStrategy">
                <a-select v-model:value="uploadConfig.categoryStrategy" placeholder="选择分类策略">
                  <a-select-option value="ai">AI生成</a-select-option>
                  <a-select-option value="custom">自定义分类</a-select-option>
                  <a-select-option value="none">不设置分类</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8" v-if="uploadConfig.categoryStrategy === 'custom'">
              <a-form-item label="自定义分类" name="customCategory">
                <a-input v-model:value="uploadConfig.customCategory" placeholder="请输入分类名称" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="上传空间" name="spaceId">
                <a-select
                  v-model:value="uploadConfig.spaceId"
                  placeholder="选择上传空间"
                  allow-clear
                >
                  <a-select-option :value="undefined">
                    <GlobalOutlined style="margin-right: 8px" />
                    公共空间
                  </a-select-option>
                  <a-select-option v-for="space in mySpaces" :key="space.id" :value="space.id">
                    <component
                      :is="space.spaceType === 0 ? UserOutlined : TeamOutlined"
                      style="margin-right: 8px"
                    />
                    {{ space.spaceName }}
                    <a-tag
                      :color="getSpaceLevelColor(space.spaceLevel)"
                      size="small"
                      style="margin-left: 8px"
                    >
                      {{ getSpaceLevelText(space.spaceLevel) }}
                    </a-tag>
                  </a-select-option>
                </a-select>
                <div style="font-size: 12px; color: #666; margin-top: 4px">
                  仅显示您创建或加入的空间
                </div>
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-item label="AI处理方式" name="asyncAiProcess">
                <a-select
                  :value="uploadConfig.asyncAiProcess ? 'true' : 'false'"
                  @update:value="(val: string) => (uploadConfig.asyncAiProcess = val === 'true')"
                >
                  <a-select-option value="true">异步处理（推荐）</a-select-option>
                  <a-select-option value="false" disabled>同步处理</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>

          <!-- WebSocket连接状态 -->
          <a-row v-if="uploadConfig.tagStrategy === 'ai' || uploadConfig.categoryStrategy === 'ai'">
            <a-col :span="24">
              <a-alert
                :type="isConnected ? 'success' : isConnecting ? 'info' : 'warning'"
                :message="getWebSocketStatusMessage()"
                :description="getWebSocketStatusDescription()"
                show-icon
                style="margin-top: 16px"
              >
                <template #action>
                  <a-button
                    v-if="!isConnected && !isConnecting"
                    size="small"
                    type="primary"
                    @click="connect"
                  >
                    重新连接
                  </a-button>
                </template>
              </a-alert>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <!-- 文件上传区域 -->
      <div class="upload-area">
        <a-upload-dragger
          v-model:file-list="fileList"
          name="files"
          multiple
          accept="image/*"
          :before-upload="beforeUpload"
          @remove="handleRemove"
          :show-upload-list="{ showRemoveIcon: true, showPreviewIcon: true }"
          @preview="handlePreview"
        >
          <p class="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p class="ant-upload-text">点击或拖拽文件到此区域上传</p>
          <p class="ant-upload-hint">支持单个或批量上传图片文件，支持 JPG、PNG、GIF、WEBP 格式</p>
        </a-upload-dragger>
      </div>

      <!-- 操作按钮 -->
      <div class="upload-actions">
        <a-space>
          <a-button
            type="primary"
            size="large"
            :loading="uploading"
            :disabled="fileList.length === 0"
            @click="handleStartUpload"
          >
            <template #icon><UploadOutlined /></template>
            开始上传 ({{ fileList.length }} 个文件)
          </a-button>
          <a-button size="large" @click="handleClearFiles" :disabled="uploading">
            <template #icon><DeleteOutlined /></template>
            清空文件
          </a-button>
          <a-button
            v-if="uploadResult"
            size="large"
            @click="handleClearResults"
            :disabled="uploading"
          >
            <template #icon><DeleteOutlined /></template>
            清空结果
          </a-button>
        </a-space>
      </div>

      <!-- 上传进度 -->
      <div v-if="uploading || uploadResult" class="upload-progress">
        <a-card size="small" title="上传进度">
          <div v-if="uploading || (uploadResult && overallProgress < 100)" class="progress-info">
            <a-progress :percent="overallProgress" :status="progressStatus" />
            <div class="progress-text">
              <span v-if="uploading">
                正在上传第 {{ currentUploadIndex }} / {{ totalFiles }} 个文件...
              </span>
              <span v-else-if="uploadResult && overallProgress < 100">
                AI处理中... ({{ overallProgress.toFixed(2) }}%)
              </span>
            </div>
          </div>

          <!-- 简洁的上传结果 -->
          <div v-if="uploadResult && overallProgress >= 100" class="upload-result-simple">
            <a-alert
              :type="uploadResult.failureCount > 0 ? 'warning' : 'success'"
              :message="getResultTitle()"
              :description="getResultSubTitle()"
              show-icon
              style="margin-bottom: 16px"
            >
              <template #action>
                <a-space>
                  <a-button
                    size="small"
                    type="primary"
                    @click="handleContinueUpload"
                    v-if="uploadResult.failureCount > 0"
                  >
                    重试失败项
                  </a-button>
                  <a-button size="small" @click="handleReset">重新上传</a-button>
                </a-space>
              </template>
            </a-alert>

            <!-- 成功上传的图片预览 -->
            <div v-if="uploadResult.successCount > 0" class="success-preview">
              <div class="preview-header">
                <span class="preview-title">上传成功 ({{ uploadResult.successCount }})</span>
              </div>
              <div class="preview-grid">
                <div
                  v-for="item in uploadResult.successList.slice(0, 8)"
                  :key="item.id"
                  class="preview-item"
                >
                  <div class="preview-image">
                    <img :src="item.thumbnailUrl || item.url" :alt="item.name" />
                    <!-- AI处理状态指示器 -->
                    <div v-if="getAiProcessStatus(item.id)" class="ai-status-indicator">
                      <component
                        :is="getAiProcessIcon(getAiProcessStatus(item.id)?.status || 'pending')"
                        class="status-icon-small"
                      />
                    </div>
                  </div>
                  <div class="preview-info">
                    <div class="preview-name">{{ truncateText(item.name, 12) }}</div>
                    <div class="preview-size">{{ formatFileSize(item.picSize) }}</div>
                  </div>
                </div>
                <div v-if="uploadResult.successList.length > 8" class="preview-more">
                  +{{ uploadResult.successList.length - 8 }}
                </div>
              </div>
            </div>

            <!-- 失败列表 -->
            <div v-if="uploadResult.failureCount > 0" class="failure-list">
              <a-collapse size="small">
                <a-collapse-panel key="failure" :header="`上传失败 (${uploadResult.failureCount})`">
                  <div class="failure-items">
                    <div
                      v-for="item in uploadResult.failureList"
                      :key="item.fileName"
                      class="failure-item"
                    >
                      <div class="failure-name">{{ item.fileName }}</div>
                      <div class="failure-reason">{{ item.failureReason }}</div>
                    </div>
                  </div>
                </a-collapse-panel>
              </a-collapse>
            </div>
          </div>
        </a-card>
      </div>
    </a-card>

    <!-- 图片预览弹窗 -->
    <a-modal
      v-model:open="previewVisible"
      :title="previewTitle"
      :footer="null"
      centered
      width="60%"
    >
      <img :src="previewImage" style="width: 100%" />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, h, watch, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  InboxOutlined,
  UploadOutlined,
  DeleteOutlined,
  SyncOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  GlobalOutlined,
  UserOutlined,
  TeamOutlined,
} from '@ant-design/icons-vue'
import { batchUploadPictures } from '@/api/picture'
import type { PictureBatchUploadRequest, PictureBatchUploadVO } from '@/types/picture'
import type { UploadFile } from 'ant-design-vue'
import { useWebSocket } from '@/composables/useWebSocket'
import type { AiProcessStatus } from '@/types/websocket'
import { getMySpaces } from '@/api/space'
import type { SpaceVO } from '@/types/space'
import { getSpaceLevelText, getSpaceLevelColor } from '@/types/space'
import { useUserStore } from '@/stores/user'

// 组件props
interface Props {
  defaultSpaceId?: string // 雪花算法ID，使用string避免精度丢失
}

const props = withDefaults(defineProps<Props>(), {
  defaultSpaceId: undefined,
})

const userStore = useUserStore()

// WebSocket连接
const { isConnected, isConnecting, connect, clearAllAiProcessStatuses, aiProcessStatuses } =
  useWebSocket()

// 响应式数据
const fileList = ref<UploadFile[]>([])
const uploading = ref(false)
const uploadResult = ref<PictureBatchUploadVO | null>(null)
const previewVisible = ref(false)
const previewImage = ref('')
const previewTitle = ref('')
const uploadProgress = ref(0)
const uploadStatus = ref<'active' | 'success' | 'exception'>('active')
const currentUploadIndex = ref(0)
const aiProcessingPictures = ref<Map<number, AiProcessStatus>>(new Map())
const mySpaces = ref<SpaceVO[]>([])

// 上传配置
const uploadConfig = reactive<PictureBatchUploadRequest>({
  nameStrategy: 'auto', // 改为自动命名
  namePrefix: 'auto',
  tagStrategy: 'ai', // 使用AI生成标签
  customTags: [],
  categoryStrategy: 'ai', // 使用AI生成分类
  customCategory: '',
  spaceId: undefined, // 默认上传到公共空间
  asyncAiProcess: true, // 使用异步AI处理
})

// 计算属性
const totalFiles = computed(() => fileList.value.length)

// 计算总体进度（上传+AI处理）
const overallProgress = computed(() => {
  if (!uploadResult.value) return uploadProgress.value

  const { successList } = uploadResult.value
  if (successList.length === 0) return 100

  // 如果不需要AI处理，直接返回100%
  if (uploadConfig.tagStrategy !== 'ai' && uploadConfig.categoryStrategy !== 'ai') {
    return 100
  }

  // 计算AI处理完成的数量
  let completedAiTasks = 0
  successList.forEach((picture) => {
    const status = getAiProcessStatus.value(picture.id)
    if (status && (status.status === 'success' || status.status === 'error')) {
      completedAiTasks++
    }
  })

  // 上传占50%，AI处理占50%
  const uploadPercent = uploading.value ? uploadProgress.value * 0.5 : 50
  const aiPercent = (completedAiTasks / successList.length) * 50

  return Number((uploadPercent + aiPercent).toFixed(2))
})

// 计算进度状态
const progressStatus = computed(() => {
  if (uploadStatus.value === 'exception') return 'exception'
  if (overallProgress.value >= 100) return 'success'
  return 'active'
})

// 获取AI处理状态的计算属性，确保响应式更新
const getAiProcessStatus = computed(() => {
  return (pictureId: string) => {
    const globalStatus = aiProcessStatuses.get(pictureId as unknown as number)
    const localStatus = aiProcessingPictures.value.get(pictureId as unknown as number)
    console.log(`获取图片 ${pictureId} 的AI状态 - 全局:`, globalStatus, '本地:', localStatus)
    return globalStatus || localStatus
  }
})

// 文件上传前的检查
const beforeUpload = (file: UploadFile) => {
  const isImage = file.type?.startsWith('image/')
  if (!isImage) {
    message.error('只能上传图片文件！')
    return false
  }

  const isLt10M = (file.size || 0) / 1024 / 1024 < 10
  if (!isLt10M) {
    message.error('图片大小必须小于 10MB！')
    return false
  }

  // 检查是否已存在相同文件
  const isDuplicate = fileList.value.some(
    (item) => item.name === file.name && item.size === file.size,
  )
  if (isDuplicate) {
    message.warning('文件已存在，请勿重复添加')
    return false
  }

  return false // 阻止自动上传
}

// 移除文件
const handleRemove = (file: UploadFile) => {
  const index = fileList.value.indexOf(file)
  const newFileList = fileList.value.slice()
  newFileList.splice(index, 1)
  fileList.value = newFileList
}

// 预览图片
const handlePreview = async (file: UploadFile) => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj as File)
  }
  previewImage.value = file.url || (file.preview as string)
  previewVisible.value = true
  previewTitle.value = file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1)
}

// 获取文件的 base64 编码
const getBase64 = (file: File): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result as string)
    reader.onerror = (error) => reject(error)
  })
}

// 开始上传
const handleStartUpload = async () => {
  if (fileList.value.length === 0) {
    message.warning('请先选择要上传的文件')
    return
  }

  try {
    uploading.value = true
    uploadProgress.value = 0
    uploadStatus.value = 'active'
    currentUploadIndex.value = 0
    uploadResult.value = null

    // 获取实际的文件对象
    const files = fileList.value.map((file) => file.originFileObj as File)

    // 模拟上传进度
    const progressTimer = setInterval(() => {
      if (uploadProgress.value < 90) {
        uploadProgress.value += Math.random() * 10
        currentUploadIndex.value = Math.min(
          Math.floor((uploadProgress.value / 100) * files.length) + 1,
          files.length,
        )
      }
    }, 300)

    const response = await batchUploadPictures(files, uploadConfig)

    clearInterval(progressTimer)
    uploadProgress.value = 100
    uploadStatus.value = response.data.failureCount > 0 ? 'exception' : 'success'
    uploadResult.value = response.data
    currentUploadIndex.value = files.length

    // 如果有成功上传的文件，清空文件列表
    if (response.data.successCount > 0) {
      fileList.value = []
    }

    const { successCount, failureCount, hasAsyncTask, successList } = response.data
    if (failureCount === 0) {
      message.success(`批量上传成功！共上传 ${successCount} 个文件`)
    } else if (successCount === 0) {
      message.error(`批量上传失败！共 ${failureCount} 个文件上传失败`)
    } else {
      message.warning(`部分上传成功！成功 ${successCount} 个，失败 ${failureCount} 个`)
    }

    // 处理AI异步任务
    if (hasAsyncTask && successList.length > 0) {
      // 确保WebSocket连接
      if (!isConnected.value && !isConnecting.value) {
        try {
          await connect()
        } catch (error) {
          console.error('建立WebSocket连接失败:', error)
          message.warning('AI处理通知连接失败，无法实时显示处理进度')
        }
      }

      // 初始化AI处理状态
      successList.forEach((picture) => {
        if (uploadConfig.tagStrategy === 'ai' || uploadConfig.categoryStrategy === 'ai') {
          const aiStatus = {
            pictureId: picture.id,
            status: 'pending' as const,
            message: '等待AI处理...',
            timestamp: new Date().toISOString(),
          }
          aiProcessingPictures.value.set(picture.id as unknown as number, aiStatus)
          console.log(`初始化AI处理状态 - 图片ID: ${picture.id}, 状态:`, aiStatus)
          console.log(
            `当前上传结果中的图片ID列表:`,
            successList.map((p) => p.id),
          )
          console.log(`全局AI状态Map:`, aiProcessStatuses)
        }
      })

      message.info(`AI标签生成任务已在后台运行，共${successList.length}张图片等待处理`)
    }
  } catch (error) {
    console.error('批量上传失败:', error)
    message.error('批量上传失败')
    uploadStatus.value = 'exception'
  } finally {
    uploading.value = false
  }
}

// 清空文件列表
const handleClearFiles = () => {
  fileList.value = []
  // 不清空 uploadResult，让用户能看到上传结果和AI处理状态
  // uploadResult.value = null
  uploadProgress.value = 0
}

// 清空上传结果
const handleClearResults = () => {
  uploadResult.value = null
  aiProcessingPictures.value.clear()
  uploadProgress.value = 0
}

// 获取我的空间列表
const fetchMySpaces = async () => {
  try {
    const response = await getMySpaces()
    // 打印调试信息
    console.log('当前用户ID:', userStore.loginUser?.id, typeof userStore.loginUser?.id)
    console.log('所有空间列表:', response.data.records)

    // 筛选出属于当前用户的空间
    mySpaces.value = response.data.records.filter(
      (space) => space.userId === userStore.loginUser?.id,
    )

    console.log('过滤后的用户空间:', mySpaces.value)
    // 打印每个空间的用户ID和类型用于调试
    response.data.records.forEach((space) => {
      console.log(
        `空间 ${space.spaceName} - userId: ${space.userId} (${typeof space.userId}), 匹配: ${space.userId === userStore.loginUser?.id}`,
      )
    })
  } catch (error) {
    console.error('获取空间列表失败:', error)
    // 不显示错误消息，空间列表为空时用户仍可以上传到公共空间
    // 如果后端空间接口尚未实现，设置为空数组
    mySpaces.value = []
  }
}

// 重置上传
const handleReset = () => {
  handleClearFiles()
  uploadConfig.nameStrategy = 'auto' // 改为自动命名
  uploadConfig.namePrefix = 'auto' // 设置默认前缀
  uploadConfig.tagStrategy = 'ai' // 使用AI生成标签
  uploadConfig.customTags = []
  uploadConfig.categoryStrategy = 'ai' // 使用AI生成分类
  uploadConfig.customCategory = ''
  uploadConfig.spaceId = undefined // 重置为公共空间
  uploadConfig.asyncAiProcess = true // 使用异步AI处理
  // 清空AI处理状态
  aiProcessingPictures.value.clear()
  clearAllAiProcessStatuses()
}

// 继续上传失败的文件
const handleContinueUpload = () => {
  if (!uploadResult.value?.failureList.length) return

  // 重新创建失败文件的文件列表
  const failedFileNames = uploadResult.value.failureList.map((item) => item.fileName)
  fileList.value = fileList.value.filter((file) => failedFileNames.includes(file.name))

  uploadResult.value = null
  handleStartUpload()
}

// 获取结果标题
const getResultTitle = () => {
  if (!uploadResult.value) return ''
  const { successCount, failureCount } = uploadResult.value
  if (failureCount === 0) {
    return `批量上传成功！`
  } else if (successCount === 0) {
    return `批量上传失败！`
  } else {
    return `部分上传成功！`
  }
}

// 获取结果副标题
const getResultSubTitle = () => {
  if (!uploadResult.value) return ''
  const { totalCount, successCount, failureCount } = uploadResult.value
  return `总计 ${totalCount} 个文件，成功 ${successCount} 个，失败 ${failureCount} 个`
}

// 格式化文件大小
const formatFileSize = (bytes?: number) => {
  if (!bytes) return '-'
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(1024))
  return Math.round((bytes / Math.pow(1024, i)) * 100) / 100 + ' ' + sizes[i]
}

// 截断文本
const truncateText = (text: string, maxLength: number) => {
  if (!text) return ''
  if (text.length <= maxLength) return text
  return text.substring(0, maxLength) + '...'
}

// 获取AI处理状态图标
const getAiProcessIcon = (status: AiProcessStatus['status']) => {
  switch (status) {
    case 'pending':
      return h(SyncOutlined, { spin: true, style: { color: '#1890ff' } })
    case 'processing':
      return h(SyncOutlined, { spin: true, style: { color: '#1890ff' } })
    case 'success':
      return h(CheckCircleOutlined, { style: { color: '#52c41a' } })
    case 'error':
      return h(ExclamationCircleOutlined, { style: { color: '#ff4d4f' } })
    default:
      return null
  }
}

// 获取WebSocket状态消息
const getWebSocketStatusMessage = () => {
  if (isConnected.value) {
    return 'AI处理通知已连接'
  } else if (isConnecting.value) {
    return '正在连接AI处理通知服务...'
  } else {
    return 'AI处理通知未连接'
  }
}

// 获取WebSocket状态描述
const getWebSocketStatusDescription = () => {
  if (isConnected.value) {
    return '您将实时收到AI处理进度通知'
  } else if (isConnecting.value) {
    return '请稍候，正在建立连接...'
  } else {
    return '无法实时获取AI处理进度，请检查网络连接'
  }
}

// 监听全局AI处理状态变化
watch(
  () => aiProcessStatuses,
  (statuses) => {
    console.log('收到全局AI处理状态更新:', statuses)
    console.log('statuses类型:', typeof statuses, 'size:', statuses?.size)

    // 更新本地的AI处理状态显示
    if (statuses && statuses.size > 0) {
      statuses.forEach((status, pictureId) => {
        console.log(`更新图片 ${pictureId} 的AI处理状态:`, status)
        aiProcessingPictures.value.set(pictureId, status)
      })

      // 强制触发响应式更新
      console.log('当前本地AI处理状态:', aiProcessingPictures.value)
    }
  },
  { deep: true, immediate: true },
)

// 监听AI策略变化，按需连接WebSocket
watch(
  [() => uploadConfig.tagStrategy, () => uploadConfig.categoryStrategy],
  async ([newTagStrategy, newCategoryStrategy], [oldTagStrategy, oldCategoryStrategy]) => {
    const needsAI = newTagStrategy === 'ai' || newCategoryStrategy === 'ai'
    const previouslyNeededAI = oldTagStrategy === 'ai' || oldCategoryStrategy === 'ai'

    if (needsAI && !previouslyNeededAI && !isConnected.value && !isConnecting.value) {
      // 用户刚选择了AI处理，建立连接
      try {
        await connect()
      } catch (error) {
        console.error('建立WebSocket连接失败:', error)
      }
    } else if (!needsAI && previouslyNeededAI && isConnected.value) {
      // 用户取消了AI处理，可以断开连接（可选）
      // disconnect() // 暂时保持连接，避免频繁连接断开
    }
  },
  { immediate: true }, // 不在初始化时立即执行
)

// 组件挂载时获取空间列表
onMounted(async () => {
  await fetchMySpaces()

  // 如果传入了默认空间ID，设置为默认值
  if (props.defaultSpaceId) {
    uploadConfig.spaceId = props.defaultSpaceId
  }
})
</script>

<style scoped>
.batch-upload-container {
  padding: 24px;
}

.upload-config {
  margin-bottom: 24px;
  padding: 24px;
  background: #fafafa;
  border-radius: 8px;
}

.upload-area {
  margin-bottom: 24px;
}

.upload-progress {
  margin-bottom: 24px;
}

.progress-info {
  text-align: center;
  padding: 24px;
}

.progress-text {
  margin-top: 12px;
  color: #666;
  font-size: 14px;
}

.upload-result {
  padding: 24px;
}

.result-details {
  margin-top: 24px;
}

.success-item-info {
  font-size: 12px;
  color: #666;
}

.success-item-info div {
  margin-bottom: 4px;
}

.ai-process-status {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-top: 4px;
  font-size: 11px;
}

.status-icon {
  display: inline-flex;
  align-items: center;
  margin-right: 4px;
}

.status-text {
  color: #666;
  font-size: 11px;
}

.failure-item-size {
  color: #666;
  font-size: 12px;
}

.upload-actions {
  text-align: center;
  padding: 24px;
  border-top: 1px solid #f0f0f0;
}

:deep(.ant-upload-drag) {
  padding: 48px 24px;
}

:deep(.ant-upload-drag-icon) {
  font-size: 48px;
  color: #1890ff;
}

:deep(.ant-upload-text) {
  font-size: 16px;
  font-weight: 500;
  margin: 16px 0 8px;
}

:deep(.ant-upload-hint) {
  color: #999;
  font-size: 14px;
}

:deep(.ant-card-head-title) {
  font-size: 18px;
  font-weight: 600;
}

:deep(.ant-collapse-header) {
  font-weight: 500;
}

:deep(.ant-result-title) {
  font-size: 20px;
}

/* 简洁的上传结果样式 */
.upload-result-simple {
  padding: 16px 0;
}

.success-preview {
  margin-top: 16px;
}

.preview-header {
  margin-bottom: 12px;
}

.preview-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.preview-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 12px;
  max-height: 240px;
  overflow-y: auto;
}

.preview-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.preview-image {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.preview-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.ai-status-indicator {
  position: absolute;
  top: 4px;
  right: 4px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  width: 18px;
  height: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.status-icon-small {
  font-size: 12px;
}

.preview-info {
  margin-top: 6px;
  text-align: center;
  width: 100%;
}

.preview-name {
  font-size: 12px;
  color: #333;
  margin-bottom: 2px;
}

.preview-size {
  font-size: 11px;
  color: #666;
}

.preview-more {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 80px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  color: #666;
  font-size: 14px;
  font-weight: 500;
}

.failure-list {
  margin-top: 16px;
}

.failure-items {
  max-height: 200px;
  overflow-y: auto;
}

.failure-item {
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.failure-item:last-child {
  border-bottom: none;
}

.failure-name {
  font-size: 13px;
  color: #333;
  margin-bottom: 4px;
}

.failure-reason {
  font-size: 12px;
  color: #ff4d4f;
}
</style>
